package com.sptpc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.sptpc.domain.User;
import com.sptpc.service.UserService;
import com.sptpc.utils.UUIDUtils;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="loginUI")
	public String logiUI(){
		
		return "login";
	}
	
	@RequestMapping(value="registerUI")
	public String registerUI(){
		return "register";
	}
	
	@RequestMapping(value="register",method=RequestMethod.POST)
	public ModelAndView register(User user){
		ModelAndView mv = new ModelAndView("register");
		
		user.setUid(UUIDUtils.getUuids());
		
		int n = userService.register(user);
		
		if(n>0){
			mv = new ModelAndView("login");
		}
		return mv;
		
	}
	
	@RequestMapping(value="login",method=RequestMethod.POST)
	public ModelAndView login(String username,String password,HttpSession session){
		ModelAndView mv = new ModelAndView("login");
		
		User user = userService.fingUserByNameAndPwd(username,password);
		
		
		if(user != null){
			mv = new ModelAndView("redirect:/");
			session.setAttribute("user",user);
		}else{
			mv.addObject("msg","用户名或者密码错误");
		}
		return mv;
	}
	
	@RequestMapping(value="logout")
	public String logout(HttpSession session){
		if(session.getAttribute("user") != null){
			session.removeAttribute("user");
		}
		return "redirect:/";
	}
}
